package com.CommunityHub.kiana.controller;

import com.CommunityHub.kiana.po.VenueInfo;
import com.CommunityHub.kiana.service.VenueInfoService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Collections;
import java.util.List;

@WebServlet("/VenueInfoListServlet")
public class VenueInfoListServlet extends HttpServlet {
    private VenueInfoService venueInfoService;

    @Override
    public void init() throws ServletException {
        try {
            // 初始化服务层
            venueInfoService = new VenueInfoService();
        } catch (Exception e) {
            throw new ServletException("初始化 VenueInfoService 失败", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("收到 GET 请求，转交至 POST 处理");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        // 获取并校验 action 参数
        String action = req.getParameter("action");
        if (action == null || action.isEmpty()) {
            listVenues(req, resp); // 默认列出场馆
            return;
        }

        // 处理不同 action
        try {
            switch (action) {
                case "view":
                    viewVenueDetails(req, resp);
                    break;
                case "edit":
                    editVenue(req, resp);
                    break;
                case "changeStatus":
                    changeVenueStatus(req, resp);
                    break;
                case "update": // 添加对 update action 的处理
                    updateVenue(req, resp);
                    break;
                case "add":
                    addVenue(req, resp);
                    break;
                case "delete":
                    deleteVenues(req,resp);
                    break;
                default:
                    listVenues(req, resp);
                    break;
            }
        } catch (Exception e) {
            // 统一异常处理
            req.setAttribute("error", "处理请求失败：" + e.getMessage());
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        }
    }
    private void deleteVenues(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取场馆ID参数
        String venueIdStr = req.getParameter("venueId");

        // 参数校验
        if (venueIdStr == null || venueIdStr.isEmpty()) {
            req.setAttribute("error", "场馆ID不能为空");
            listVenues(req, resp); // 返回场馆列表页并显示错误
            return;
        }

        try {
            int venueId = Integer.parseInt(venueIdStr);

            // 执行删除操作
            boolean success = venueInfoService.deleteVenue(venueId);

            if (success) {
                // 删除成功，设置成功消息并重定向到列表页
                req.getSession().setAttribute("successMessage", "场馆删除成功");
            } else {
                // 删除失败（可能场馆不存在）
                req.setAttribute("error", "未找到指定场馆或删除失败");
            }

            // 重定向回场馆列表页
            resp.sendRedirect("VenueInfoListServlet");

        } catch (NumberFormatException e) {
            req.setAttribute("error", "无效的场馆ID格式");
            listVenues(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "系统错误: " + e.getMessage());
            listVenues(req, resp);
        }
    }

    // 在doPost方法中添加
    private void addVenue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取表单数据
            String venueName = request.getParameter("venueName");
            String venueType = request.getParameter("venueType");
            int usageStatus = Integer.parseInt(request.getParameter("usageStatus"));
            String address = request.getParameter("address");
            String location = request.getParameter("location");
            String openingTime = request.getParameter("openingTime");
            String closingTime = request.getParameter("closingTime");
            String responsibleId = request.getParameter("responsibleId");
            String contactPhone = request.getParameter("contactPhone");
            BigDecimal size = new BigDecimal(request.getParameter("size"));
            String specialNote = request.getParameter("specialNote");
            BigDecimal chargeStandard = new BigDecimal(request.getParameter("chargeStandard"));

            // 创建VenueInfo对象
            VenueInfo newVenue = new VenueInfo();
            newVenue.setVenueName(venueName);
            newVenue.setVenueType(venueType);
            newVenue.setUsageStatus(usageStatus);
            newVenue.setAddress(address);
            newVenue.setLocation(location);
            newVenue.setOpeningTime(Time.valueOf(openingTime));
            newVenue.setClosingTime(Time.valueOf(closingTime));
            newVenue.setResponsibleId(Integer.valueOf(responsibleId));
            newVenue.setContactPhone(contactPhone);
            // 从请求参数获取size
            String sizeStr = request.getParameter("size");
// 使用字符串构造函数创建BigDecimal，避免精度丢失
            size = new BigDecimal(sizeStr);
            newVenue.setSize(size);
            newVenue.setSpecialNote(specialNote);
            newVenue.setChargeStandard(chargeStandard);

            // 调用Service层添加方法
            venueInfoService.addVenue(newVenue);

            // 重定向到列表页面
            response.sendRedirect("VenueInfoListServlet");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "添加场馆失败: " + e.getMessage());
            request.getRequestDispatcher("venueList.jsp").forward(request, response);
        }
    }

    // 列出场馆信息（带筛选）
    private void listVenues(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String venueType = req.getParameter("venueType");
        String usageStatusStr = req.getParameter("usageStatus");
        String location = req.getParameter("location");

        Integer usageStatus = null;
        if (usageStatusStr != null && !usageStatusStr.isEmpty()) {
            try {
                usageStatus = Integer.parseInt(usageStatusStr);
            } catch (NumberFormatException e) {
                req.setAttribute("error", "参数错误：使用状态格式不正确");
                req.setAttribute("venueInfos", Collections.emptyList());
                forwardToJsp(req, resp, "logisticsStewardHome.jsp");
                return;
            }
        }

        try {
            List<VenueInfo> venues = venueInfoService.getVenuesByFilters(venueType, usageStatus, location);
            req.setAttribute("venueInfos", venues);

            // 回显筛选条件
            req.setAttribute("selectedVenueType", venueType);
            req.setAttribute("selectedUsageStatus", usageStatusStr);
            req.setAttribute("selectedLocation", location);

            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("error", "获取场馆列表失败：数据库错误");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "获取场馆列表失败：" + e.getMessage());
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        }
    }

    // 查看场馆详情
    private void viewVenueDetails(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String venueIdStr = req.getParameter("venueId");

        // 校验 venueId 参数
        if (venueIdStr == null || venueIdStr.isEmpty()) {
            req.setAttribute("error", "参数错误：缺少场馆 ID");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
            return;
        }

        try {
            int venueId = Integer.parseInt(venueIdStr);
            VenueInfo venueInfo = venueInfoService.getVenueById(venueId);

            // 校验查询结果
            if (venueInfo == null) {
                req.setAttribute("error", "场馆不存在，ID: " + venueId);
                req.setAttribute("venueInfos", Collections.emptyList());
                forwardToJsp(req, resp, "logisticsStewardHome.jsp");
                return;
            }

            req.setAttribute("venueInfo", venueInfo);
            req.getRequestDispatcher("venueDetail.jsp").forward(req, resp);
        } catch (NumberFormatException e) {
            req.setAttribute("error", "参数错误：场馆 ID 格式不正确");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("error", "获取场馆详情失败：数据库错误");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        }
    }

    // 编辑场馆信息
    private void editVenue(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String venueIdStr = req.getParameter("venueId");

        // 校验 venueId 参数
        if (venueIdStr == null || venueIdStr.isEmpty()) {
            req.setAttribute("error", "参数错误：缺少场馆 ID");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
            return;
        }

        try {
            int venueId = Integer.parseInt(venueIdStr);
            VenueInfo venueInfo = venueInfoService.getVenueById(venueId);

            // 校验查询结果
            if (venueInfo == null) {
                req.setAttribute("error", "场馆不存在，ID: " + venueId);
                req.setAttribute("venueInfos", Collections.emptyList());
                forwardToJsp(req, resp, "logisticsStewardHome.jsp");
                return;
            }

            req.setAttribute("venueInfo", venueInfo);
            req.getRequestDispatcher("editVenue.jsp").forward(req, resp);
        } catch (NumberFormatException e) {
            req.setAttribute("error", "参数错误：场馆 ID 格式不正确");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("error", "获取场馆信息失败：数据库错误");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        }
    }

    // 更新场馆信息
    // 更新场馆信息（修复版）
    private void updateVenue(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8"); // 确保中文正常返回
        try {
            // 1. 获取基础参数并校验
            // 场馆ID（必须为正整数）
            String venueIdStr = req.getParameter("venueId");
            if (venueIdStr == null || venueIdStr.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆ID不能为空");
            }
            int venueId;
            try {
                venueId = Integer.parseInt(venueIdStr.trim());
                if (venueId <= 0) {
                    throw new IllegalArgumentException("场馆ID必须为正整数");
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("场馆ID必须为有效数字");
            }

            // 场馆名称（非空校验）
            String venueName = req.getParameter("venueName");
            if (venueName == null || venueName.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆名称不能为空");
            }
            venueName = venueName.trim(); // 去除首尾空格

            // 场馆类型（非空且必须是指定选项）
            String venueType = req.getParameter("venueType");
            if (venueType == null || venueType.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆类型不能为空");
            }
            venueType = venueType.trim();
            // 校验是否为允许的类型（与前端选项对应）
            if (!"文娱类".equals(venueType) && !"运动类".equals(venueType)
                    && !"康养类".equals(venueType) && !"综合类".equals(venueType)) {
                throw new IllegalArgumentException("场馆类型必须为：文娱类、运动类、康养类、综合类");
            }

            // 使用状态（只能是0或1）
            String usageStatusStr = req.getParameter("usageStatus");
            if (usageStatusStr == null || usageStatusStr.trim().isEmpty()) {
                throw new IllegalArgumentException("使用状态不能为空");
            }
            int usageStatus;
            try {
                usageStatus = Integer.parseInt(usageStatusStr.trim());
                if (usageStatus != 0 && usageStatus != 1) {
                    throw new IllegalArgumentException("使用状态只能是0（维护中）或1（开放中）");
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("使用状态必须为数字（0或1）");
            }

            // 场馆地址（非空）
            String address = req.getParameter("address");
            if (address == null || address.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆地址不能为空");
            }
            address = address.trim();

            // 场馆位置（非空且必须是指定选项）
            String location = req.getParameter("location");
            if (location == null || location.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆位置不能为空");
            }
            location = location.trim();
            // 校验是否为允许的位置（与前端选项对应）
            if (!"阳光花园".equals(location) && !"康养新区".equals(location) && !"魔仙堡".equals(location)) {
                throw new IllegalArgumentException("场馆位置必须为：阳光花园、康养新区、魔仙堡");
            }

            // 2. 时间处理（HH:MM:SS格式）
            String openingTimeStr = req.getParameter("openingTime");
            String closingTimeStr = req.getParameter("closingTime");
            Time openingTime = null;
            Time closingTime = null;

            // 开放时间校验
            if (openingTimeStr == null || openingTimeStr.trim().isEmpty()) {
                throw new IllegalArgumentException("开放时间不能为空");
            }
            openingTimeStr = openingTimeStr.trim();
            if (openingTimeStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) {
                openingTime = Time.valueOf(openingTimeStr);
            } else {
                throw new IllegalArgumentException("开放时间格式错误，必须为HH:MM:SS（如08:30:00）");
            }

            // 关闭时间校验
            if (closingTimeStr == null || closingTimeStr.trim().isEmpty()) {
                throw new IllegalArgumentException("关闭时间不能为空");
            }
            closingTimeStr = closingTimeStr.trim();
            if (closingTimeStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) {
                closingTime = Time.valueOf(closingTimeStr);
            } else {
                throw new IllegalArgumentException("关闭时间格式错误，必须为HH:MM:SS（如18:00:00）");
            }

            // 校验关闭时间不能早于开放时间
            if (closingTime.before(openingTime)) {
                throw new IllegalArgumentException("关闭时间不能早于开放时间");
            }

            // 3. 负责人和联系电话处理
            // 负责人ID（必须为正整数）
            String responsibleIdStr = req.getParameter("responsibleId");
            if (responsibleIdStr == null || responsibleIdStr.trim().isEmpty()) {
                throw new IllegalArgumentException("负责人编号不能为空");
            }
            int responsibleId;
            try {
                responsibleId = Integer.parseInt(responsibleIdStr.trim());
                if (responsibleId <= 0) {
                    throw new IllegalArgumentException("负责人编号必须为正整数");
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("负责人编号必须为有效数字");
            }

            // 联系电话（非空且简单格式校验）
            String contactPhone = req.getParameter("contactPhone");
            if (contactPhone == null || contactPhone.trim().isEmpty()) {
                throw new IllegalArgumentException("联系电话不能为空");
            }
            contactPhone = contactPhone.trim();
            // 简单校验：11位数字（可根据实际需求调整）
            if (!contactPhone.matches("^1[3-9]\\d{9}$")) {
                throw new IllegalArgumentException("联系电话格式错误（请输入11位手机号）");
            }

            // 4. 场馆大小（BigDecimal类型）
            String sizeParam = req.getParameter("size");
            if (sizeParam == null || sizeParam.trim().isEmpty()) {
                throw new IllegalArgumentException("场馆大小不能为空");
            }
            BigDecimal size;
            try {
                size = new BigDecimal(sizeParam.trim());
                // 校验必须为正数且最多保留2位小数（面积通常保留两位小数）
                if (size.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new IllegalArgumentException("场馆大小必须为正数");
                }
                // 检查小数位数（最多2位）
                if (size.scale() > 2) {
                    throw new IllegalArgumentException("场馆大小最多保留2位小数（如100.50）");
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("场馆大小格式错误，必须为有效数字（如100.5）");
            }

            // 5. 其他参数处理
            // 特别说明（可为空，去除首尾空格）
            String specialNote = req.getParameter("specialNote");
            if (specialNote != null) {
                specialNote = specialNote.trim();
            }

            // 收费标准（只能是0或1）
            String chargeStandardStr = req.getParameter("chargeStandard");
            if (chargeStandardStr == null || chargeStandardStr.trim().isEmpty()) {
                throw new IllegalArgumentException("收费标准不能为空");
            }
            BigDecimal chargeStandard;
            try {
                chargeStandard = new BigDecimal(chargeStandardStr.trim());
                /*if (chargeStandard != 0 && chargeStandard != 1) {
                    throw new IllegalArgumentException("收费标准只能是0（免费）或1（收费）");
                }*/
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("收费标准必须为数字（0或1）");
            }

            // 6. 创建VenueInfo对象并赋值
            VenueInfo venueInfo = new VenueInfo();
            venueInfo.setVenueId(venueId);
            venueInfo.setVenueName(venueName);
            venueInfo.setVenueType(venueType);
            venueInfo.setUsageStatus(usageStatus);
            venueInfo.setAddress(address);
            venueInfo.setLocation(location);
            venueInfo.setOpeningTime(openingTime);
            venueInfo.setClosingTime(closingTime);
            venueInfo.setResponsibleId(responsibleId);
            venueInfo.setContactPhone(contactPhone);
            venueInfo.setSize(size);
            venueInfo.setSpecialNote(specialNote);
            venueInfo.setChargeStandard(chargeStandard);

            // 7. 调用服务层更新
            venueInfoService.updateVenue(venueInfo);
            resp.getWriter().println("更新成功");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数错误：" + e.getMessage());
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新失败：" + e.getMessage());
        }
    }
    // 更改场馆状态
    private void changeVenueStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String venueIdStr = req.getParameter("venueId");

        // 校验 venueId 参数
        if (venueIdStr == null || venueIdStr.isEmpty()) {
            req.setAttribute("error", "参数错误：缺少场馆 ID");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
            return;
        }

        try {
            int venueId = Integer.parseInt(venueIdStr);
            venueInfoService.toggleVenueStatus(venueId);
            resp.sendRedirect("VenueInfoListServlet"); // 避免重复提交
        } catch (NumberFormatException e) {
            req.setAttribute("error", "参数错误：场馆 ID 格式不正确");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("error", "更改场馆状态失败：数据库错误");
            req.setAttribute("venueInfos", Collections.emptyList());
            forwardToJsp(req, resp, "logisticsStewardHome.jsp");
        }
    }

    // 封装请求转发方法
    private void forwardToJsp(HttpServletRequest req, HttpServletResponse resp, String jspPath) throws ServletException, IOException {
        // 示例：确保 jsp 文件放在 Web 应用的正确目录（如 WebContent/ 或 src/main/webapp/ 下）
        req.getRequestDispatcher(jspPath).forward(req, resp);
    }
}